package org.arduomo.serial.controller;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class SerialController implements SerialPortEventListener  {
	
	private static SerialController theInstance=null;
	SerialPort serialPort;
	/** The port we're normally going to use. */
	private static final String PORT_NAMES[] = { "/dev/tty.usbserial-A9007UX1", // Mac
																				// OS
																				// X
			"/dev/ttyUSB0", // Linux
			"COM3", // Windows
			"/dev/ttyACM0"
	};
	/** Buffered input stream from the port */
	private InputStream input;
	/** The output stream to the port */
	private OutputStream output;
	/** Milliseconds to block while waiting for port open */
	private static final int TIME_OUT = 2000;
	/** Default bits per second for COM port. */
	private static final int DATA_RATE = 115200;
	private static final int MAX_BUFFER_SIZE = 10000;
	private int numFillBuffer;
	private List<SerialListener> listeners;
	private byte buffer[] = new byte[MAX_BUFFER_SIZE];
	public SerialController() {
		super();
		listeners= new ArrayList<SerialListener>();
		initialize();
	}

	public void initialize() {
		CommPortIdentifier portId = null;
		Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

		// iterate through, looking for the port
		while (portEnum.hasMoreElements()) {
			CommPortIdentifier currPortId = (CommPortIdentifier) portEnum
					.nextElement();
			for (String portName : PORT_NAMES) {
				if (currPortId.getName().equals(portName)) {
					portId = currPortId;
					break;
				}
			}
		}

		if (portId == null) {
			System.out.println("Could not find COM port.");
			return;
		}

		try {
			// open serial port, and use class name for the appName.
			serialPort = (SerialPort) portId.open(this.getClass().getName(),
					TIME_OUT);

			// set port parameters
			serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8,
					SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

			// open the streams
			input = serialPort.getInputStream();
			output = serialPort.getOutputStream();

			// add event listeners
			serialPort.addEventListener(this);
			serialPort.notifyOnDataAvailable(true);
		} catch (Exception e) {
			System.err.println(e.toString());
		}
	}

	/**
	 * This should be called when you stop using the port. This will prevent
	 * port locking on platforms like Linux.
	 */
	public synchronized void close() {
		if (serialPort != null) {
			serialPort.removeEventListener();
			serialPort.close();
		}
	}

	/**
	 * Handle an event on the serial port. Read the data and print it.
	 */
	public synchronized void serialEvent(SerialPortEvent oEvent) {
		if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
			try {
				int available = input.available();
				
				numFillBuffer+=input.read(buffer, numFillBuffer, available);
				if (buffer[numFillBuffer-1]=='\n') {
					for (SerialListener sl : listeners) {
						sl.receivedMessage(new String(buffer,0,numFillBuffer));
					}
					numFillBuffer=0;
				}

//				// Displayed results are codepage dependent
//				System.out.print(new String(chunk));
			} catch (Exception e) {
//				System.err.println(e.toString());
				e.printStackTrace();
			}
		}
		// Ignore all the other eventTypes, but you should consider the other
		// ones.
	}
	
	public synchronized void sendMessage(String message) throws Exception{
		try {
			output.write(message.getBytes());
		} catch (IOException e) {
			e.printStackTrace();
			throw new Exception("Could not send message",e);
		}
	}

	public static SerialController getInstance() {
		if (theInstance==null) {
			theInstance = new SerialController();
		}
		return theInstance;
	}

	public void addListener(SerialListener listener){
		if (!listeners.contains(listener)) {
			listeners.add(listener);
		}
	}
	
	public void removeListener(SerialListener listener){
		if (listeners.contains(listener)) {
			listeners.remove(listener);
		}
	}
	
	
}
